//
//  ManyPageViewController.m
//  FCTools
//
//  Created by WJC on 2018/10/25.
//  Copyright © 2018 wjc. All rights reserved.
//

#import "ManyPageViewController.h"
#import "WJCDefine.h"
#import "imageCollectionViewCell.h"
#import "UIView+viewExtension.h"
#import "UIColor+Random.h"
@interface ManyPageViewController ()<UIScrollViewDelegate>
@property (nonatomic,assign) CGFloat lastScroll;
@property (nonatomic,assign) CGFloat naviH;

@end

@implementation ManyPageViewController
-(NSMutableArray *)contentCotrollerArr{
    if (!_contentCotrollerArr) {
        _contentCotrollerArr =[NSMutableArray new];
    }
    return _contentCotrollerArr;
}
-(NSMutableArray *)topBtnArr{
    if (!_topBtnArr) {
        _topBtnArr =[NSMutableArray new];
    }
    return _topBtnArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor=[UIColor whiteColor];
    if IPhoneX{
        self.naviH=88;
    }
    if (self.topTitle.count==self.contentCotrollerArr.count&&self.topTitle.count>0) {
        [self setContent];
    }

}
-(void)setContent{
    [self.view removeChildViews];
    if (self.topTitle.count!=self.contentCotrollerArr.count) {
        [self showAlertError:@"顶部文字和控制器数量要一样"];
        return;
    }
    else if(self.topTitle.count&&self.topTitle.count>0){
        [self setTableContent];
    }
    else{
       [self showAlertError:@"找不到创建按钮数据"];
    }
}
-(void)setToTopScroll:(CGFloat)toTopScroll{
    _toTopScroll=toTopScroll;
     if (self.topTitle.count==1) {
         self.contentScrollView.y=toTopScroll;
          self.contentScrollView.height=WJCScreenH-self.naviH-toTopScroll;
         self.contentScrollView.contentSize=CGSizeMake(self.contentScrollView.contentSize.width, self.contentScrollView.height);
         for (UIView *v in self.contentScrollView.subviews) {
             v.height=self.contentScrollView.height;
         }
         
     }else{
    self.scrollView.y=toTopScroll;
    self.contentScrollView.y=self.scrollView.y+self.scrollView.height;
         self.contentScrollView.height=WJCScreenH-self.scrollView.height-self.naviH-toTopScroll;
          self.contentScrollView.contentSize=CGSizeMake(self.contentScrollView.contentSize.width, self.contentScrollView.height);
         for (UIView *v in self.contentScrollView.subviews) {
             v.height=self.contentScrollView.height;
         }
     }
}
-(void)refreshTopScroll{
    if (self.topTitle.count!=self.contentCotrollerArr.count) {
        
        [self showAlertError:@"顶部文字和控制器数量要一样"];
        return;
    }
    [_scrollView removeChildViews];
    self.topBtnArr=[NSMutableArray new];
    if(self.topTitle.count>5){
        _scrollView.contentSize=CGSizeMake(self.scrollView.frame.size.width*0.25*self.topTitle.count, _scrollView.height);
    }
    for (int i=0; i<self.topTitle.count; i++) {
        UIButton *lastBtn;
        if (self.topBtnArr.count>0) {
            lastBtn=self.topBtnArr.lastObject;
        }
       
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.zPosition = 999;
        [btn setTitleColor:self.btnColor?self.btnColor:HEXC(0x232323) forState:UIControlStateNormal];
        
        btn.titleLabel.font=font15;
        btn.frame=CGRectMake(lastBtn?lastBtn.frame.origin.x+lastBtn.frame.size.width:0,0 , self.scrollView.frame.size.width/self.topTitle.count, _scrollView.height-2);
        btn.centerY =(_scrollView.height-2)*0.5;
        [btn setTitle:self.topTitle[i] forState:UIControlStateNormal];
        if(self.topTitle.count>4){
            btn.frame=CGRectMake(lastBtn?lastBtn.frame.origin.x+lastBtn.frame.size.width:0, 0, _scrollView.width*0.25, _scrollView.height-2);
        }
        btn.tag=i;
        [btn addTarget:self action:@selector(topClick:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *l=[[UILabel alloc]init];
        l.font=font15;
        l.text=self.topTitle[i];
        [l sizeToFit];
        if (l.frame.size.width>btn.frame.size.width||self.topTitle.count>4) {
            btn.frame=CGRectMake(btn.frame.origin.x, btn.frame.origin.y, l.frame.size.width+32, btn.frame.size.height);
        }
        [_scrollView addSubview:btn];
        [self.topBtnArr addObject:btn];
        WJCWeakSelf
        if (self.currentPage>0) {
            if (i==self.currentPage) {
                    [weakSelf.topLineView removeFromSuperview];
                    [btn setTitleColor:self.topTitleSelectColor?self.topTitleSelectColor:HEXC(0x238EFA) forState:UIControlStateNormal];
                if (self.topTitleSelectBackColor) {
                    [btn setBackgroundColor:self.topTitleSelectBackColor];
                }
                    weakSelf.topLineView=[[UIView alloc]initWithFrame:CGRectMake(btn.centerX-btn.width*0.3, weakSelf.topLineHeight>0?(weakSelf.scrollView.height-(weakSelf.topLineHeight>0?weakSelf.topLineHeight:2))*0.5:weakSelf.scrollView.height-4, btn.width*0.6, weakSelf.topLineHeight?weakSelf.topLineHeight:2)];
                    weakSelf.topLineView.backgroundColor=self.lineColor;
                    [weakSelf.scrollView addSubview:weakSelf.topLineView];
                    btn.titleLabel.font=font(self.topTitleSelectFont);
                if (btn.frame.origin.x+btn.size.width>WJCScreenW) {
                   [weakSelf.scrollView setContentOffset:CGPointMake(weakSelf.scrollView.contentOffset.x+(weakSelf.topBtnArr[weakSelf.currentPage].frame.origin.x+ weakSelf.topBtnArr[weakSelf.currentPage].frame.size.width-WJCScreenW), 0) animated:NO];
                }
            }
        }else{
            if (i==0) {
                    [btn setTitleColor:self.topTitleSelectColor?self.topTitleSelectColor:HEXC(0x238EFA) forState:UIControlStateNormal];
                if (self.topTitleSelectBackColor) {
                    [btn setBackgroundColor:self.topTitleSelectBackColor];
                }
                    [weakSelf.topLineView removeFromSuperview];
                    weakSelf.topLineView=[[UIView alloc]initWithFrame:CGRectMake(btn.centerX-btn.width*0.3, weakSelf.topLineHeight>0?(weakSelf.scrollView.height-(weakSelf.topLineHeight>0?weakSelf.topLineHeight:2))*0.5:weakSelf.scrollView.height-4, btn.width*0.6, weakSelf.topLineHeight?weakSelf.topLineHeight:2)];
                    weakSelf.topLineView.backgroundColor=self.lineColor;
                    [weakSelf.scrollView addSubview:weakSelf.topLineView];
                btn.titleLabel.font=font(self.topTitleSelectFont);
            }
            
        }
        if(i==self.topTitle.count-1){
            _scrollView.contentSize=CGSizeMake(btn.frame.origin.x+btn.frame.size.width, _scrollView.height);
        }
    }
    if (self.topBtnArr.lastObject.width+self.topBtnArr.lastObject.x<WJCScreenW&&self.topBtnArr.count>4) {
        for (int i = 0; i <self.topBtnArr.count; i++) {
            self.topBtnArr[i].frame=CGRectMake(i==0 ? 0: (self.topBtnArr[i-1].frame.origin.x+self.topBtnArr[i-1].frame.size.width), 0, WJCScreenW*0.25, _scrollView.height-2);
        }
        _scrollView.contentSize=CGSizeMake(WJCScreenW*0.25*self.topBtnArr.count, _scrollView.height);
    }
    if (self.topTitle.count==1) {
        self.scrollView.hidden=YES;
        self.contentScrollView.frame=CGRectMake(0, 0, WJCScreenW,  WJCScreenH-self.naviH);
    }
}
-(void)setTableContent{
    if (self.topTitle.count!=self.contentCotrollerArr.count&&self.contentCotrollerArr.count>self.topTitle.count) {
        
       [self showAlertError:@"顶部文字和控制器数量要一样"];
        return;
    }
    if (self.contentScrollView) {
        [self.contentScrollView removeFromSuperview];
         self.contentScrollView = nil;
        
    }
    
    [_scrollView removeChildViews];
    _scrollView=nil;
    
    if (!self.topHeight) {
        self.topHeight = 44;
    }
    if (!self.topLineHeight) {
         self.topLineHeight =1;
    }
   
    
    if (!self.btnColor) {
        self.btnColor = HEXC(0x232323);
    }
    if (!self.topTitleSelectColor) {
        self.topTitleSelectColor =HEXC(0x238EFA);
    }
    if (!self.topTitleSelectFont) {
        self.topTitleSelectFont = 15;
    }
    if (!self.lineColor) {
        self.lineColor = self.topTitleSelectBackColor ? self.topTitleSelectBackColor :HEXC(0x238EFA);
    }
    
    _scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WJCScreenW,self.topHeight)];
    self.naviH=64;
    [self.view addSubview:_scrollView];
    
    
    self.contentScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, self.topHeight, WJCScreenW,  WJCScreenH-self.topHeight-self.naviH)];
    _contentScrollView.delegate=self;
    [self.view addSubview:_contentScrollView];
    
    _contentScrollView.pagingEnabled=YES;
    _contentScrollView.showsVerticalScrollIndicator=NO;
    _contentScrollView.showsHorizontalScrollIndicator=NO;
    _contentScrollView.contentSize=CGSizeMake(WJCScreenW*self.topTitle.count, WJCScreenH-self.topHeight-self.naviH);
    self.topBtnArr=[NSMutableArray new];
    
    _scrollView.showsVerticalScrollIndicator=NO;
    _scrollView.showsHorizontalScrollIndicator=NO;
    if(self.topTitle.count>5){
        _scrollView.contentSize=CGSizeMake(self.scrollView.frame.size.width*0.25*self.topTitle.count, self.topHeight);
    }
//    UIView *lineView=[UIView new];
//    lineView.backgroundColor=HEXC(0xD8D8D8);
//    lineView.frame=CGRectMake(0, 43.5, WJCScreenW*2, 0.5);
//    [_scrollView addSubview:lineView];
    for (int i=0; i<self.topTitle.count; i++) {
        [self addChildViewController:self.contentCotrollerArr[i]];
        [((UIViewController*)self.contentCotrollerArr[i]) didMoveToParentViewController:self];
        [((UIViewController*)self.contentCotrollerArr[i]).view setFrame:CGRectMake(WJCScreenW*i, 0, WJCScreenW, WJCScreenH-self.naviH-self.topHeight)];
        [_contentScrollView addSubview:((UIViewController*)self.contentCotrollerArr[i]).view];
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:self.btnColor forState:UIControlStateNormal];
        if (self.btnBackColor) {
            [btn setBackgroundColor:self.btnBackColor];
        }
        btn.layer.zPosition = 999;
        btn.titleLabel.font= font15;
       
        btn.frame=CGRectMake(self.topBtnArr.lastObject.frame.origin.x+self.topBtnArr.lastObject.frame.size.width+self.btnInset, 4, self.scrollView.frame.size.width/self.topTitle.count, self.topHeight-8);
//        FCLRViewBorderRadius(btn, btn.height*0.5, 1, self.btnColor);
        [btn setTitle:self.topTitle[i] forState:UIControlStateNormal];
        if(self.topTitle.count>4){
            btn.frame=CGRectMake(self.topBtnArr.lastObject.frame.origin.x+self.topBtnArr.lastObject.frame.size.width+self.btnInset, 4, WJCScreenW*0.25, self.topHeight-8);
        }
        btn.tag=i;
        [btn addTarget:self action:@selector(topClick:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *l=[[UILabel alloc]init];
        l.font=btn.titleLabel.font;
        l.text=self.topTitle[i];
        [l sizeToFit];
        if (l.frame.size.width>btn.frame.size.width||self.topTitle.count>4) {
            btn.frame=CGRectMake(btn.frame.origin.x, btn.frame.origin.y, l.frame.size.width+32, btn.frame.size.height);
        }
        [_scrollView addSubview:btn];
        [self.topBtnArr addObject:btn];
        WJCWeakSelf
        if (self.currentPage>0) {
            if (i==self.currentPage) {
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [weakSelf.topLineView removeFromSuperview];
                    [btn setTitleColor:self.topTitleSelectColor?self.topTitleSelectColor:HEXC(0x238EFA) forState:UIControlStateNormal];
                    
                    weakSelf.topLineView=[[UIView alloc]initWithFrame:CGRectMake(weakSelf.topBtnArr[self.currentPage].centerX-weakSelf.topBtnArr[self.currentPage].width*0.3,weakSelf.topLineHeight<=2?(weakSelf.scrollView.height-2):((weakSelf.scrollView.height-weakSelf.topLineHeight)*0.5), weakSelf.topBtnArr[self.currentPage].width*0.6, weakSelf.topLineHeight?weakSelf.topLineHeight:2)];
                    WJCSETLRViewBorderRadius(weakSelf.topLineView, weakSelf.topLineView.height*0.5);
//                    weakSelf.topLineView.layer.cornerRadius = 1;
                    weakSelf.topLineView.layer.masksToBounds = YES;
                    weakSelf.topLineView.backgroundColor=self.lineColor;
                    [weakSelf.scrollView addSubview:weakSelf.topLineView];
//                    [weakSelf.scrollView bringSubviewToFront:weakSelf.topLineView];
//                    weakSelf.topLineView.layer.zPosition = 9999;
                    [weakSelf.contentScrollView setContentOffset:CGPointMake(weakSelf.contentScrollView.frame.size.width*weakSelf.currentPage, 0) animated:NO];
                    btn.titleLabel.font=font(self.topTitleSelectFont);
                });
            }
        }else{
            if (i==0) {
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [btn setTitleColor:self.topTitleSelectColor?self.topTitleSelectColor:HEXC(0x238EFA) forState:UIControlStateNormal];
                    [weakSelf.topLineView removeFromSuperview];
                   
                    weakSelf.topLineView=[[UIView alloc]initWithFrame:CGRectMake(weakSelf.topBtnArr[0].centerX-weakSelf.topBtnArr[0].width*0.3,weakSelf.topLineHeight<=2?(weakSelf.scrollView.height-2):((weakSelf.scrollView.height-weakSelf.topLineHeight)*0.5), weakSelf.topBtnArr[0].width*0.6, weakSelf.topLineHeight?weakSelf.topLineHeight:2)];
                    WJCSETLRViewBorderRadius(weakSelf.topLineView, weakSelf.topLineView.height*0.5);
                    weakSelf.topLineView.backgroundColor=self.lineColor;
//                    weakSelf.topLineView.layer.zPosition = 9999;
                    [weakSelf.scrollView addSubview:weakSelf.topLineView];
//                    [weakSelf.scrollView bringSubviewToFront:weakSelf.topLineView];
                    weakSelf.topLineView.layer.masksToBounds = YES;
                    btn.titleLabel.font=font(self.topTitleSelectFont);
                });
            }
            if(i==self.topTitle.count-1){
                _scrollView.contentSize=CGSizeMake(btn.frame.origin.x+btn.frame.size.width, 44);
            }
        }
    }
    if (self.topBtnArr.lastObject.width+self.topBtnArr.lastObject.x<WJCScreenW&&self.topBtnArr.count>4) {
        for (int i = 0; i <self.topBtnArr.count; i++) {
            self.topBtnArr[i].frame=CGRectMake(i==0 ? 0: (self.topBtnArr[i-1].frame.origin.x+self.topBtnArr[i-1].frame.size.width), 0, WJCScreenW*0.25, 43);
        }
        _scrollView.contentSize=CGSizeMake(WJCScreenW*0.25*self.topBtnArr.count, 44);
    }
    if (self.topTitle.count==1) {
        self.scrollView.hidden=YES;
        self.contentScrollView.frame=CGRectMake(0, 0, WJCScreenW,  WJCScreenH-self.naviH);//[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WJCScreenW,  WJCScreenH-self.naviH)];
    }
    if ([self.delegate respondsToSelector:@selector(resetScrollViewWithTopScrollView:andContentScrollView:)]) {
        [self.delegate resetScrollViewWithTopScrollView:_scrollView andContentScrollView:_contentScrollView];;
    }
}
-(void)topClick:(UIButton*)sender{
    if ([self.delegate respondsToSelector:@selector(topBtnClickWithButton:)]) {
        if ([self.delegate topBtnClickWithButton:sender]) {
            WJCWeakSelf
            self.lastScroll = _contentScrollView.contentOffset.x;
            [UIView animateWithDuration:0.25 animations:^{
                [weakSelf.contentScrollView setContentOffset:CGPointMake(weakSelf.contentScrollView.frame.size.width*sender.tag, 0)];
            } completion:^(BOOL finished) {
                if (finished) {
                    [weakSelf scrollViewDidEndDecelerating:weakSelf.contentScrollView];
                }
                
            }];
        }
        
    }else{
        WJCWeakSelf
        self.lastScroll = _contentScrollView.contentOffset.x;
        [UIView animateWithDuration:0.25 animations:^{
            [weakSelf.contentScrollView setContentOffset:CGPointMake(weakSelf.contentScrollView.frame.size.width*sender.tag, 0)];
        } completion:^(BOOL finished) {
            if (finished) {
                [weakSelf scrollViewDidEndDecelerating:weakSelf.contentScrollView];
            }
            
        }];
    }
}

-(void)setCurrentPage:(NSInteger)currentPage{
   
    _currentPage=currentPage;
    WJCWeakSelf
    [self.contentScrollView setContentOffset:CGPointMake(_contentScrollView.frame.size.width*currentPage, 0) animated:self.currentPageAnimate];

}
#pragma mark--delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.currentPage=round(scrollView.contentOffset.x / scrollView.frame.size.width);
    self.lastScroll = scrollView.contentOffset.x;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
      
}
    //结束滑动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int currentPageNum = round(scrollView.contentOffset.x / scrollView.frame.size.width);
    
    for (UIButton *btn in self.topBtnArr) {
        [btn setTitleColor:self.btnColor ? self.btnColor : HEXC(0x232323) forState:UIControlStateNormal];
        btn.titleLabel.font = font(15);
    }
    WJCWeakSelf
    [weakSelf.scrollView bringSubviewToFront:weakSelf.topBtnArr[currentPageNum]];
        //    if(currentPageNum !=self.currentPage){
    [UIView animateWithDuration:0.25 animations:^{
        
        weakSelf.topBtnArr[currentPageNum].titleLabel.font=font(self.topTitleSelectFont);
//        CGRectMake(btn.centerX-16, btn.height-(weakSelf.topLineHeight>0?weakSelf.topLineHeight:2), 40, weakSelf.topLineHeight?weakSelf.topLineHeight:2)
        weakSelf.topLineView.frame=CGRectMake(weakSelf.topBtnArr[currentPageNum].centerX-weakSelf.topBtnArr[currentPageNum].width*0.3,weakSelf.topLineHeight<=2?(weakSelf.scrollView.height-2):((weakSelf.scrollView.height-weakSelf.topLineHeight)*0.5), weakSelf.topBtnArr[currentPageNum].width*0.6, weakSelf.topLineHeight?weakSelf.topLineHeight:2);
        WJCSETLRViewBorderRadius(weakSelf.topLineView, weakSelf.topLineView.height*0.5);
        if (currentPageNum!=weakSelf.currentPage) {
            if (self.lastScroll<scrollView.contentOffset.x) {
                if (currentPageNum>0) {
                    if (self.topBtnArr[currentPageNum].right>weakSelf.scrollView.frame.size.width&&weakSelf.scrollView.contentSize.width>weakSelf.scrollView.width*1.05) {
                        [weakSelf.scrollView setContentOffset:CGPointMake(weakSelf.topBtnArr[currentPageNum].right-weakSelf.scrollView.frame.size.width, 0) animated:YES];
                    }
                }
            }else if (weakSelf.lastScroll>scrollView.contentOffset.x){
                if (weakSelf.topBtnArr.count>currentPageNum) {
                    UIWindow *win= [UIApplication sharedApplication].keyWindow;
                    CGRect rect = [weakSelf.topLineView convertRect:weakSelf.scrollView.frame toView:win];
                    if (rect.origin.x<0&&weakSelf.scrollView.contentSize.width>weakSelf.scrollView.width*1.05) {
                        [weakSelf.scrollView setContentOffset:CGPointMake(weakSelf.topBtnArr[currentPageNum].x-self.btnInset, 0) animated:YES];
                    }
                }
            }
        }
        self.currentPage=currentPageNum;
    } completion:^(BOOL finished) {
        [weakSelf.topBtnArr[currentPageNum] setTitleColor:self.topTitleSelectColor?self.topTitleSelectColor:HEXC(0x238EFA) forState:UIControlStateNormal];
    }];
    
    
        //    }
    if ([self.delegate respondsToSelector:@selector(scrollViewdidScrollWithScrollView:andContentScrollView:andCurrentPage:)]) {
        [self.delegate scrollViewdidScrollWithScrollView:_scrollView andContentScrollView:_contentScrollView andCurrentPage:currentPageNum];
    }
//    self.title=self.topTitle[currentPageNum];
}

    // 判断View是否显示在屏幕上
- (BOOL)isDisplayedInScreenWithView:(UIView*)view
{
    if (view == nil) {
        return NO;
    }
    
    CGRect screenRect = [UIScreen mainScreen].bounds;
    
        // 转换view对应window的Rect
    UIWindow *win= [UIApplication sharedApplication].keyWindow;
    CGRect rect = [view convertRect:view.frame toView:win];
    if (CGRectIsEmpty(rect) || CGRectIsNull(rect)) {
        return NO;
    }
    
        // 若view 隐藏
    if (view.hidden) {
        return NO;
    }
    
        // 若没有superview
    if (view.superview == nil) {
        return NO;
    }
    
        // 若size为CGrectZero
    if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
        return  NO;
    }
    
        // 获取 该view与window 交叉的 Rect
    CGRect intersectionRect = CGRectIntersection(rect, screenRect);
    if (CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)) {
        return NO;
    }
    
    return YES;
}
-(void)showAlertError:(NSString*)str{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:^{ }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
